const compressImage = (file) => new Promise((resolve) => {
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');

  let img = new Image();
  let url = URL.createObjectURL(file);

  img.onload = () => {
    URL.revokeObjectURL(url);

    let w, h;

    const ratio = img.height / img.width;
    w = Math.min(600, img.width);
    h = w * ratio;

    canvas.width = w;
    canvas.height = h;

    ctx.drawImage(img, 0, 0, w, h);
    canvas.toBlob(blob => {
      const f = new File([blob], file.name, {
        type: file.type,
        lastModified: file.lastModified
      });
      resolve(f);
    }, 'image/png');
  }
  
  img.src = url;
})

export default compressImage;